import {routerRedux} from 'dva/router';
import {message} from 'antd';
import { indexGroupGoods, saveIndexGroupGoods, indexGroupDetail, deleteIndexGroupGoods, saveAddIndexGroupGoods } from '../services/api';

export default {
  namespace: 'indexGroupGoods',
  state: {
    data: [],
    detail : {}
  },

  effects: {
    *fetch({payload}, {call, put}){
      const res = yield call(indexGroupGoods, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {data: res}
        });
      }
    },
    *fetchDetail({payload}, {call, put}){
      const res = yield call(indexGroupDetail, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {detail: res}
        });
      }
    },
    *changeWeight({payload}, {call, put}){
      const { id, value} = payload;
      const res = yield call(saveIndexGroupGoods, payload);
      if (res) {
        yield put({
          type: 'saveWeight',
          payload: payload
        });
      }
    },
    *addGoods({payload}, {call, put}){  //新增商品
      const res = yield call(saveAddIndexGroupGoods, {
        id : payload.id,
        goodsIds : payload.goods.map(v=>v.id)

      });
      if (res) {
        yield put({
          type : 'saveAdd',
          payload : payload
        });
        return res;
      }
    },
    *deleteItem({payload}, {call, put}){  //移除商品
      const res = yield call(deleteIndexGroupGoods, payload);
      if (res) {
        yield put({
          type : 'saveDelete',
          payload : payload
        });
        return res;
      }
    },
  },

  reducers: {
    save(state, {payload}){
      return {
        ...state,
        ...payload
      }
    },
    saveWeight(state, {payload}){
      let data = {...state.data};
      data.list.forEach((v,i)=>{
        if(v.id == payload.goodsId){
          v.weight = payload.weight;
        }
      });
      data.list.sort((a, b)=>{
        return a.weight < b.weight
      });
      return {
        ...state,
        ...{data:data}
      }
    },
    celar(state, {payload}){
      return {
        data: [],
        detail : {},
      }
    },
    saveDelete(state, { payload }){
      let data = {...state.data};
      data.list.forEach((v,i)=>{
        if(v.id == payload.goodsIds[0]){
          data.list.splice(i,1);
        }
      });
      return {
        ...state,
        ...{data:data}
      }
    },
    saveAdd(state, { payload }){
      let data = {...state.data};
      payload.goods.forEach(goods=>{
        let contain = false; //是否包含
        for(var i = 0; i < data.list.length; i++){
          if(goods.id == data.list[i].id){
            contain = true;
            break;
          }
        }
        if(!contain){  //未包含添加到最前面
          data.list.unshift(goods);
        }
      });
      return {
        ...state,
        ...{data:data}
      }
    },
  },
};
